from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from api.serializer.account import LoginSerializer, MessageSerializer
from rest_framework import serializers
import random
from django_redis import get_redis_connection
from api import models
# from utils.tencent.msg import send_message
from utils.ronglian.sms import send_message
import uuid
from utils.tencent.term_key import TemporaryKey
from rest_framework.generics import CreateAPIView, ListAPIView, RetrieveAPIView, GenericAPIView
from api.authentication.auth import GeneralAuthentication, UserAuthentication
from api.serializer.news import NewsDetailModelSerializer, NewsModelSerializer, NewsDetailViewModel, \
    FavorModelSerializer, ChildFavorModelSerializer
from api.serializer.comment import CommentModelSerializer, CreateCommentModelSerializer
from rest_framework import status
from api.pagination.pages import MaxBaseFilterBackend, MinBaseFilterBackend, NewsListLimitOffsetPagination
from django.db.models import F
import requests


class LoginView(APIView):
    def post(self, request, *args, **kwargs):
        ser = LoginSerializer(data=request.data)

        if not ser.is_valid():
            print(ser.errors)
            return Response({'status': False, 'message': ser.errors.get('code')[0]})
        phone = ser.validated_data.get('phone')
        nickname = ser.validated_data.get('nickname')
        avatar = ser.validated_data.get('avatar')
        # 获取openid(需要拿着wx_code去申请)
        wx_code = ser.validated_data.get('wx_code')

        # info = {
        #     'appid': "wxe459ac5ae8f95261",
        #     'secret': "363c2392a215f7591ef8d6f3e616c173",
        #     'js_code': wx_code,
        #     'grant_type': "authorization_code"
        # }
        # result = requests.get(url="https://api.weixin.qq.com/sns/jscode2session", params=info)
        # print(result.json())

        user_object, flag = models.UserInfo.objects.get_or_create(phone=phone, nickname=nickname, avatar=avatar)
        user_object.token = str(uuid.uuid4())
        user_object.save()
        return Response({'status': True, 'data': {"token": user_object.token, "phone": phone}})


class MessageView(APIView):
    def get(self, request, *args, **kwargs):
        ser = MessageSerializer(data=request.query_params)
        if not ser.is_valid():
            print(ser.errors)
            return Response({'status': False, 'message': ser.errors['phone'][0]})
        phone = request.query_params.get('phone')

        random_code = str(random.randint(1000, 9999))
        # send_message(phone, random_code)
        print(random_code)
        conn = get_redis_connection()
        conn.set(phone, random_code, ex=60)
        return Response({"status": True, "message": "发送成功"})


class CredentialView(APIView):
    def get(self, *args, **kwargs):
        data = TemporaryKey()
        return Response(data, status=status.HTTP_201_CREATED)


class NewsView(CreateAPIView, ListAPIView):
    serializer_class = [NewsDetailModelSerializer, NewsModelSerializer]
    queryset = models.News.objects.all().order_by("-id")
    pagination_class = NewsListLimitOffsetPagination
    filter_backends = [MinBaseFilterBackend, MaxBaseFilterBackend]

    # 通过CreateAPIView先执行perform_create调用sava方法通过create保存
    def perform_create(self, serializer):
        return serializer.save()

    def get_serializer_class(self):
        if self.request.method == "POST":
            return NewsDetailModelSerializer

        if self.request.method == "GET":
            return NewsModelSerializer


class NewsDetailView(RetrieveAPIView):
    queryset = models.News.objects
    serializer_class = NewsDetailViewModel
    authentication_classes = [GeneralAuthentication]

    def get(self, request, *args, **kwargs):
        response = super().get(request, *args, **kwargs)
        if not request.user:
            return response
        # 获取news对象
        news_object = self.get_object()
        exists = models.ViewerRecord.objects.filter(news=news_object, user=request.user).exists()
        if exists:
            return response
        models.ViewerRecord.objects.create(news=news_object, user=request.user)
        models.News.objects.filter(id=news_object.id).update(viewer_count=F('viewer_count') + 1)
        return response


class CommentView(ListAPIView):
    queryset = models.CommentRecord.objects
    serializer_class = CommentModelSerializer

    def get_authenticators(self):
        if self.request.method == "POST":
            return [UserAuthentication(), ]
        return [GeneralAuthentication(), ]

    # 重写list方法
    def list(self, request, *args, **kwargs):
        root_id = request.query_params.get('root_id')
        node_queryset = self.get_queryset().filter(root_id=root_id)
        queryset = self.filter_queryset(node_queryset)
        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)

        serializer = self.get_serializer(queryset, many=True)
        return Response(serializer.data, status=status.HTTP_200_OK)

    def post(self, request, *args, **kwargs):
        ser = CreateCommentModelSerializer(data=request.data)
        if ser.is_valid():
            token = request.data.get('token')
            news_id = request.data.get('news')
            user_object = models.UserInfo.objects.filter(token=token).first()
            ser.save(user=user_object)
            models.News.objects.filter(id=news_id).update(comment_count=F('comment_count') + 1)
            return Response(ser.data, status=status.HTTP_201_CREATED)
        return Response(ser.errors, status=status.HTTP_400_BAD_REQUEST)


class FavorView(APIView):
    authentication_classes = [UserAuthentication, ]

    def post(self, request, *args, **kwargs):
        ser = FavorModelSerializer(data=request.data)
        # 如果校验失败(不能为空)
        if not ser.is_valid():
            return Response({}, status=status.HTTP_400_BAD_REQUEST)
        news_object = ser.validated_data.get('news')
        queryset = models.NewsFavorRecord.objects.filter(user=request.user, news=news_object)
        exists = queryset.exists()
        # 在点一次取消并删除
        if exists:
            queryset.delete()
            models.News.objects.filter(id=news_object.id).update(favor_count=F('favor_count') - 1)
            return Response({}, status=status.HTTP_200_OK)

        models.NewsFavorRecord.objects.create(news=news_object, user=request.user)
        models.News.objects.filter(id=news_object.id).update(favor_count=F('favor_count') + 1)
        return Response({}, status=status.HTTP_201_CREATED)


class ChildFavorView(APIView):
    authentication_classes = [UserAuthentication, ]

    def post(self, request, *args, **kwargs):
        ser = ChildFavorModelSerializer(data=request.data)
        # 如果校验失败(不能为空)
        if not ser.is_valid():
            return Response({}, status=status.HTTP_400_BAD_REQUEST)
        comment_object = ser.validated_data.get('comment')
        queryset = models.CommentFavorRecord.objects.filter(user=request.user, comment=comment_object)
        exists = queryset.exists()
        # 在点一次取消并删除
        if exists:
            queryset.delete()
            models.CommentRecord.objects.filter(id=comment_object.id).update(favor_count=F('favor_count') - 1)
            return Response({}, status=status.HTTP_200_OK)
        # 添加
        models.CommentFavorRecord.objects.create(comment=comment_object, user=request.user)
        models.CommentRecord.objects.filter(id=comment_object.id).update(favor_count=F('favor_count') + 1)
        return Response({}, status=status.HTTP_201_CREATED)
